package cn.cvs.controller;

import cn.cvs.pojo.Admin;
import cn.cvs.pojo.Blog;
import cn.cvs.pojo.User;
import cn.cvs.service.admin.AdminService;
import cn.cvs.service.blog.BlogService;
import cn.cvs.utils.Constants;
import cn.cvs.utils.PageSupport;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sys/admin")
public class AdminController {

    private Logger logger = Logger.getLogger(UserController.class);

    @Resource
    private AdminService adminService;


    @PostMapping("/login")
    public String login(@RequestParam(value = "name") String name,
                        @RequestParam(value ="pwd") String pwd,HttpServletRequest request,HttpSession session){

        Admin admin = adminService.selectByNameAndPwd(name, pwd);
        if (null != admin) {
            session.setAttribute(Constants.USER_ADMIN_SESSION, admin);
            return "redirect:/sys/toMain";
        } else {
            request.setAttribute("error", "用户名或密码不正确");
            return "login";
        }
    }

    @RequestMapping(value="/list")
    public String queryPageList(Model model,
                                @RequestParam(value = "name",required = false) String name,
                                @RequestParam(value ="pageIndex", defaultValue = "1") Integer pageIndex ) {
        //设置页面容量
        Integer pageSize = Constants.pageSize;

        int totalCount = adminService.count(name);

        PageSupport pages=new PageSupport();
        pages.setCurrentPageNo(pageIndex);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount = pages.getTotalPageCount();

        List<Admin> adminList = adminService.list(name, pageIndex, pageSize);

        if(pageIndex > totalPageCount){
            pageIndex = totalPageCount;
        }

        model.addAttribute("adminList", adminList);
        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("currentPageNo", pageIndex);

        return "admin/list";
    }


    @DeleteMapping(value="/del/{id}")
    @ResponseBody
    public Map<String,String> delete(@PathVariable(value = "id",required = true)Integer id){
        Map<String,String> resultMap = new HashMap<>();
        int result = adminService.deleteById(id);
        if (result > 0) {
            resultMap.put("result","true");
        } else {
            resultMap.put("result","false");
        }
        return resultMap;
    }


    /**
     * 跳转到添加页面
     * @param
     * @return
     */
    @GetMapping("/toAdd")
    public String toAdd(@ModelAttribute("admin") Admin admin){
        return "admin/add";
    }

    @PostMapping("/add")
    public String addUserSave(Admin admin, HttpSession session, HttpServletRequest request
            , @RequestParam(value ="workPic", required = false) MultipartFile workPic){
        String idPicPath = null;
        String workPicPath = null;
        String path = request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");


        //判断文件是否为空(工作证照)
        if(!workPic.isEmpty()){
            String oldFileName = workPic.getOriginalFilename();//原文件名
            logger.info("uploadFile oldFileName ============== > "+oldFileName);
            String prefix= FilenameUtils.getExtension(oldFileName);//原文件后缀
            logger.debug("uploadFile prefix============> " + prefix);
            int filesize = 500000;
            logger.debug("uploadFile size============> " + workPic.getSize());
            if(workPic.getSize() >  filesize){//上传大小不得超过 500k
                request.setAttribute("uploadWpError", " * 上传大小不得超过 500k");
                return "useradd";
            }else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                    || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
                String fileName = System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"_Personal.jpg";
                logger.debug("new fileName======== " + workPic.getName());
                File targetFile = new File(path, fileName);
                if(!targetFile.exists()){
                    targetFile.mkdirs();
                }
                //保存
                try {
                    workPic.transferTo(targetFile);
                } catch (Exception e) {
                    e.printStackTrace();
                    request.setAttribute("uploadWpError", " * 上传失败！");
                    return "sysUser/add";
                }
                workPicPath = fileName;
            }else{
                request.setAttribute("uploadWpError", " * 上传图片格式不正确");
                return "sysUser/add";
            }
        }

        try{

            admin.setPic(workPicPath);
            int i = adminService.insert(admin);
            if (i > 0) {
                return "redirect:/sys/admin/list";
            }

        }catch (Exception e){
            e.printStackTrace();
            logger.error("保存用户信息失败");
        }
        return "user/add";
    }



    /**
     * 查询申请志愿者详情信息
     * @param id
     * @param model
     * @param request
     * @return
     */
    @GetMapping("/view/{id}")
    public String view(@PathVariable Integer id, Model model, HttpServletRequest request){
        Admin admin = adminService.selectById(id);
        model.addAttribute("admin",admin);
        return "admin/update";
    }
}
